<template>
  <div class="app-container">
    <LeftNav
      ref="leftNavRef"
      @select="handleNavSelect"
      @create-form="handleCreateForm"
      @open-form-designer="handleOpenFormDesigner"
      @form-updated="handleFormUpdated"
      @open-directory-manager="handleOpenDirectoryManager"
      @preview-form="handlePreviewForm"
    />
    <div class="main-container">
      <FormDesigner
        v-if="showFormDesigner"
        :form="currentForm"
        @save="handleFormSave"
        @close="handleFormClose"
      />
      <DirectoryManager
        v-else-if="showDirectoryManager"
        :folders="navFolders"
        :availableForms="availableForms"
        @update="handleDirectoryUpdate"
        @structure-updated="handleStructureUpdated"
      />
      <FormPreview
        v-else-if="showFormPreview"
        :form="currentForm"
      />
      <div v-else class="welcome">
        <h2>Welcome to Form Management System</h2>
        <p>请从左侧菜单选择要操作的内容</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import LeftNav from './components/LeftNav.vue'
import FormDesigner from './components/FormDesigner.vue'
import DirectoryManager from './components/DirectoryManager.vue'
import FormPreview from './components/FormPreview.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Form, Folder, FormDefinition } from './types/form'

interface LeftNavExpose {
  loadNavData: () => Promise<void>
}

const API_BASE_URL = 'http://localhost:5000/api'

// 响应式状态
const leftNavRef = ref<LeftNavExpose | null>(null)
const currentForm = ref<Form | null>(null)
const showFormDesigner = ref(false)
const showDirectoryManager = ref(false)
const showFormPreview = ref(false)
const navFolders = ref<Folder[]>([])
const availableForms = ref<Form[]>([])

// 加载所有表单
const loadAvailableForms = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/form`)
    if (response.data.code === 0) {
      availableForms.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '加载表单失败')
    }
  } catch (error) {
    console.error('加载表单错误:', error)
    ElMessage.error('加载表单失败')
  }
}

// 加载目录结构
const loadFolders = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/nav/structure`)
    if (response.data.code === 0) {
      navFolders.value = response.data.data || []
    } else {
      throw new Error(response.data.message || '加载目录结构失败')
    }
  } catch (error) {
    console.error('加载目录结构错误:', error)
    ElMessage.error('加载目录结构失败')
  }
}

// 保存目录结构
const saveFolders = async (folders: Folder[]) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/nav/structure`, {
      structure: folders
    })
    if (response.data.code === 0) {
      ElMessage.success('保存成功')
      return true
    } else {
      throw new Error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存目录结构错误:', error)
    ElMessage.error('保存失败')
    return false
  }
}

const handleNavSelect = (index: string) => {
  console.log('Selected:', index)
}

const handleCreateForm = (form: Form) => {
  currentForm.value = form
  showDirectoryManager.value = false
  showFormPreview.value = false
  showFormDesigner.value = true
}

const handleOpenFormDesigner = (form: Form) => {
  currentForm.value = form
  showDirectoryManager.value = false
  showFormPreview.value = false
  showFormDesigner.value = true
}

const handleCloseFormDesigner = () => {
  currentForm.value = null
  showFormDesigner.value = false
}

const handleFormUpdated = (form: Form) => {
  if (currentForm.value && currentForm.value.id === form.id) {
    currentForm.value = form
  }
}

const handleOpenDirectoryManager = (folders: Folder[]) => {
  navFolders.value = folders
  showDirectoryManager.value = true
  showFormPreview.value = false
  currentForm.value = null
}

const handleDirectoryUpdate = async (folders: Folder[]) => {
  navFolders.value = folders
  await saveFolders(folders)
}

// 处理目录结构更新
const handleStructureUpdated = (folders: any[]) => {
  navFolders.value = folders
  if (leftNavRef.value) {
    leftNavRef.value.loadNavData()
  }
}

// 处理表单预览
const handlePreviewForm = (form: Form) => {
  currentForm.value = form
  showFormPreview.value = true
  showDirectoryManager.value = false
  showFormDesigner.value = false
}

// 处理表单保存
const handleFormSave = (form: Form) => {
  // 实现表单保存逻辑
  loadAvailableForms()
  if (leftNavRef.value) {
    leftNavRef.value.loadNavData()
  }
}

// 处理表单关闭
const handleFormClose = () => {
  showFormDesigner.value = false
  currentForm.value = null
}

// 在组件挂载时加载数据
onMounted(() => {
  loadAvailableForms()
  loadFolders()
})
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

#app {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.app-container {
  display: flex;
  height: 100vh;
}

.main-container {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  overflow: auto;
}

.welcome {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.welcome h2 {
  margin-bottom: 20px;
  color: #303133;
}
</style>
